package org.chipu.shared.util.singletons;

import java.util.*;

public class CollectionUtils {
	private CollectionUtils() {/**/}

	/**
	 * Adds the value to the list that can be found using the key. If the list does not exists yet, then it is created.
	 */
	public static <K> void addToMap(Map<K, ArrayList<Integer>> map, K key, Integer value) {
		ArrayList<Integer> v = map.get(key);
		if (v == null) {
			v = new ArrayList<Integer>();
			map.put(key, v);
		}
		v.add(value);
	}

	public static <K> void addToMap(Map<K, int[]> map, K key, int arraySize, int index, int value) {
		int[] v = map.get(key);
		if (v == null) {
			v = new int[arraySize];
			map.put(key, v);
		}
		v[index] = value;
	}

	public static <K> void addCountToMap(Map<K, Integer> map, K key) {
		Integer value = map.get(key);
		if (value == null)
			map.put(key, 1);
		else
			map.put(key, value + 1);
	}

	public static <T> T get(ListIterator<? extends T> i, int index) {
		T obj = null;
		int pos = i.nextIndex();
		if (pos <= index)
			do
				obj = i.next();
			while(pos++ < index);
		else
			do
				obj = i.previous();
			while(--pos > index);
		return obj;
	}
}